package com.wss.lsl.test.driven.runnable;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.wss.lsl.test.driven.runnable.factory.PropertyThreadFactory;

public class SimpleProperties implements Runnable {

	private int countDown = 5;
	@SuppressWarnings("unused")
	private volatile double d;
	private int name;
	private int property;

	public SimpleProperties(int name) {
		super();
		this.name = name;
	}

	public SimpleProperties(int name, int property) {
		super();
		this.name = name;
		this.property = property;
	}

	@Override
	public String toString() {
		return name + ": " + countDown;
	}

	@Override
	public void run() {
		if (property != 0) {
			Thread.currentThread().setPriority(property);
		}
		while (true) {
			for (int i = 0; i < 1000000; i++) {
				d += (Math.PI + Math.E) / (double) i;
				if (i % 1000 == 0) {
					Thread.yield();
				}
			}
			System.out.println(this);
			if (--countDown == 0) {
				return;
			}
		}
	}

	public static void main(String[] args) {

		setPropertyByRun();

		setPropertyByThreadFactory();
	}

	private static void setPropertyByRun() {
		ExecutorService exec = Executors.newCachedThreadPool();
		exec.execute(new SimpleProperties(5, Thread.MAX_PRIORITY));
		for (int i = 0; i < 5; i++) {
			exec.execute(new SimpleProperties(i, Thread.MIN_PRIORITY));
		}
		exec.shutdown();
	}

	private static void setPropertyByThreadFactory() {
		PropertyThreadFactory ptf = new PropertyThreadFactory(
				Thread.MIN_PRIORITY);
		ExecutorService exec = Executors.newCachedThreadPool(ptf);
		for (int i = 0; i < 5; i++) {
			exec.execute(new SimpleProperties(i));
		}
		ptf.setProperty(Thread.MAX_PRIORITY);
		exec.execute(new SimpleProperties(5));
		exec.shutdown();
	}

}
